﻿using Blog.Core.AuthHelper;
using Blog.Core.Data;
using Blog.Core.Model.Model;
using Blog.Core.Model.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;

namespace Blog.Core.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly ILogger<LoginController> _logger;
        private readonly IJwtHelperServices _jwtHelperServices;
        private readonly BlogContext _context;
        public LoginController(
        ILogger<LoginController> logger,
        IJwtHelperServices jwtHelperServices,
        BlogContext blogContext
        )
        {
            _logger = logger;
            _jwtHelperServices = jwtHelperServices;
            _context = blogContext;
        }
        /// <summary>
        /// 获取令牌
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<TokenDTO>> GetTokenAsync(LoginDTO userDTO)
        {

            if (string.IsNullOrEmpty(userDTO.UserName))
            {
                return NotFound();
            }
            var user = await _context.Users.FindAsync(userDTO.UserName);
            if (user == null || !user.State)
            {
                return NotFound();

            }

            if (!user.ValidatePassword(userDTO.Password))
            {
                return NotFound();
            }

            var role =await _context.UserRoles.Where(c => c.UserID == user.UserName).FirstOrDefaultAsync();
            if (role == null)
            {
                return NotFound();
            }
            //生成Token
            var tokenDTO = new TokenDTO
            {
                Token = "Bearer " + _jwtHelperServices.IssuerToken(new UserRoleDTO { UserName= user.UserName,Password = user.Password, RoleName = role.RoleID})
            };
            return tokenDTO;


        }

    }
}
